package model

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func InitGorm(dataSource string) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.Open(dataSource), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, err
	}

	// 自动迁移表结构
	err = db.AutoMigrate(&User{}, &Role{})
	if err != nil {
		return nil, err
	}

	// 初始化默认角色
	initDefaultRoles(db)

	return db, nil
}

func initDefaultRoles(db *gorm.DB) {
	roles := []Role{
		{ID: 1, Name: "super_admin", Desc: "超级管理员"},
		{ID: 2, Name: "admin", Desc: "普通管理员"},
		{ID: 3, Name: "user", Desc: "普通用户"},
		{ID: 4, Name: "vip", Desc: "VIP用户"},
	}

	for _, role := range roles {
		var existing Role
		result := db.Where("id = ?", role.ID).First(&existing)
		if result.Error != nil {
			if result.Error == gorm.ErrRecordNotFound {
				db.Create(&role)
			}
		}
	}
}
